//
//  LogisticsVC.swift
//  SlaughterClient
//
//  Created by 邱仙凯 on 2021/6/10.
//  Copyright © 2021 zwb. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZyaLogisticsVC: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource {
    
    var page = 1
    
    var dataArray = [ZyaLogisticsModel]()
    var z_zb_id = "" // 出价记录使用
    
    var keyword = ""
    var sourType = "1"
    var sortType = "1"
    var sourStatus = "0,1,2,3"
    var startDate = ""
    var endDate = ""
    var cityStr = ""
    
    let sourceTypeArr = ["全部", "采购合同类", "药品疫苗类", "耗用品类", "试剂耗材类", "环保药剂类", "办公用品类", "设备类", "燃料类", "其他类"]
    let statusArr = ["全部", "运输中", "已签收", "付款中", "已付款"]
    let dateArr = ["全部", "3日内", "7日内", "1月内", "3月内"]
    let sortArr = ["发货日期", "剩余账期"]
    
    let helper = ZyaTenderHelper()
    private var searchBar: UISearchBar?
    
    lazy var tableView: UITableView = {
        return UITableView(frame: .zero, style: .plain).then {
            $0.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
            $0.delegate = self
            $0.dataSource = self
            $0.estimatedRowHeight = 160
            $0.separatorStyle = .none
            $0.tableFooterView = UIView()
            $0.backgroundColor = UIColor(kshex: "#f3f3f3")
            $0.register(cellWithClass: ZyaLogisticsCell.self)
        }
    }()
    
    
    lazy var filterView: SlideView = {
        
        let sort = SlideContent(type: .singleSelect, title: "排序", dataArr: ["发货日期", "剩余账期"].map { SeString(title: $0, ks_selected: ($0 == "发货日期")) })
        let status = SlideContent(type: .singleSelect, title: "状态", dataArr: ["全部", "运输中", "已签收", "付款中", "已付款"].map { SeString(title: $0, ks_selected: ($0 == "全部")) })
        let period = SlideContent(type: .singleSelect, title: "剩余账期", dataArr: ["全部", "3日内", "7日内", "1月内", "3月内"].map { SeString(title: $0, ks_selected: ($0 == "全部")) })
        
        let v = SlideView(frame: CGRect(origin: .zero, size: CGSizeMake(KSGlobal.screenW, KSGlobal.screenH)), arr: [sort, status, period])
        
        v.confirmClosure = { arr in
            let sort = arr[0].dataArr?.filter { $0.ks_selected }
            if sort?.first?.title == "发货日期" {
                self.sortType = "1"
            } else {
                self.sortType = "2"
            }
            
            
            let status = arr[1].dataArr?.filter { $0.ks_selected }
            if let statusTitle = status?.first?.title {
                if statusTitle == "全部" {
                    self.sourStatus = "0,1,2,3"
                }
                if statusTitle == "运输中" {
                    self.sourStatus = "0"
                }
                if statusTitle == "已签收" {
                    self.sourStatus = "1"
                }
                if statusTitle == "付款中" {
                    self.sourStatus = "2"
                }
                if statusTitle == "已付款" {
                    self.sourStatus = "3"
                }
            } else {
                self.sourStatus = "0,1,2,3"
            }
            
        
            let period = arr[2].dataArr!.filter{ $0.ks_selected }
            if let periodTitle = period.first?.title {
                if periodTitle == "全部" {
                    self.startDate = ""
                    self.endDate = ""
                    
                } else if periodTitle == "3日内" {
                    self.startDate = Date.todayPres(3)
                    self.endDate = Date.today
                    
                } else if periodTitle == "7日内" {
                    self.startDate = Date.todayPres(7)
                    self.endDate = Date.today
                    
                } else if periodTitle == "1月内" {
                    self.startDate = Date.preMonthsWithNowday(1)
                    self.endDate = Date.today
                    
                } else if periodTitle == "3月内" {
                    self.startDate = Date.preMonthsWithNowday(3)
                    self.endDate = Date.today
                }
            } else {
                self.startDate = ""
                self.endDate = ""
            }
            
            self.filterView.close()
            self.tableView.mj_header?.beginRefreshing()
        }
        
        return v
    }()
    
    lazy var bV: UIView = {
        let v = UIView(frame: CGRect(x: 0, y: ksStatusbarHeight + ksNavigationbarHeight , width: KSGlobal.screenW, height: 40))
        return v
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "动保发货"
        
        view.backgroundColor = UIColor(kshex: "#f3f3f3")
        
        
        self.configSearch()
        
        let filterBtn = UIButton().easy("filter_more", self, #selector(filterBtnClick))
        bV.addSubview(filterBtn)
        filterBtn.snp.makeConstraints { make in
            make.top.bottom.right.equalToSuperview()
            make.width.equalTo(40)
        }
        
        bV.addSubview(searchBar!)
        view.addSubview(bV)
        
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(bV.snp.bottom).offset(3)
        }

        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
        let btn = UIButton()
        btn.setTitle("新增发货", for: .normal)
        btn.layer.masksToBounds = true
        btn.layer.cornerRadius = 20
        btn.backgroundColor = Theme.primaryColor()
        self.view.addSubview(btn)
        
        btn.snp.makeConstraints { make in
            make.bottom.equalTo(self.view).offset(-10)
            make.centerX.equalTo(self.view)
            make.width.equalTo(KSGlobal.screenW - 40)
            make.height.equalTo(40)
        }
        btn.addTouchUpInSideAction { _ in
            let vc = ZyaLogisticsFormVC.initForAdd()
            vc.refreshClosure = {
                self.tableView.mj_header?.beginRefreshing()
            }
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func configSearch() {
        searchBar = TenderSearchBar(frame:CGRect(x: 0, y: 3, width: KSGlobal.screenW - 40, height: 40))
        if #available(iOS 13.0, *) {
            searchBar!.searchTextField.backgroundColor = .white
            searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        } else {
            // Fallback on earlier versions
            let searchField = searchBar!.value(forKey: "searchField") as! UITextField
            searchField.backgroundColor = .white
            searchField.layer.cornerRadius = 18
            searchField.layer.masksToBounds = true
            
        }
        searchBar?.barTintColor = UIColor(kshex: "#f5f5f5")
        searchBar?.backgroundImage = UIImage()
        
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        searchBar!.text = self.keyword
        searchBar!.placeholder = "请输入关键字"
        searchBar!.delegate = self
    }
    
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    @objc func filterBtnClick() {
        if let window = getKeyWindow() {
            window.rootViewController?.view.addSubview(self.filterView)
        }
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.keyword = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let one = self.dataArray[indexPath.row]
        
        switch one.zStatus.unwrap {
        case "1":
            return 160
        case "2":
            return 180
        case "3":
            return 200
        default:
            return 140
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: ZyaLogisticsCell.self, for: indexPath)
        let one = self.dataArray[indexPath.row]
        cell.one = one
        cell.operateBtnGroup.clickAction = { tag, title in
            if title == "物流信息" {
                if meInfoM.member_type == "1" {
                    self.go2WLXX(index: indexPath.row)
                } else {
                    go2Member_Z(controller: self)
                }
            }
            if title == "编辑" {
                let vc = ZyaLogisticsFormVC.initForFix(idkey: self.dataArray[indexPath.row].idKey.unwrap)
                vc.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if title == "查看" {
                let vc = ZyaLogisticsFormVC.initForView(idkey: self.dataArray[indexPath.row].idKey.unwrap)
                vc.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if title == "删除" {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    KSNetwork.shared.doRequest(API.deleteLogistics(id_key: self.dataArray[indexPath.row].idKey.unwrap)) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            self.tableView.mj_header?.beginRefreshing()
                        } else {
                            KSToast(data.message.unwrap)
                        }
                    }
                })])
            }
            if title == "催款" {
                KSNetwork.shared.doRequest(API.queryLinkMan(org_code: one.zOrgId.unwrap, keyword: "")) { (data: BaseResult<ZyaAlertPerson>) in
                    if data.flag == TRUE {
                        if let infos = data.infoArrCombine {
                            
                            if infos.count > 0 {
                                
                                let alert = ZyaLogisticsDebtAlert()
                                alert.sureBlock = { persons in
                                    
                                    let totalJsonArr = persons.compactMap { dictionaryToJson($0.dictionaryRepresentation()) }
                                    
                                    var deJson = totalJsonArr.joined(separator: ",")
                                    deJson = "[\(deJson)]"
                                    
                                    KSNetwork.shared.doRequest(API.sendPaymentMessage(detail: deJson, z_ht_id: one.zContractId.unwrap)) { (data: BaseResult<OperateResult>) in
                                        KSToast(data.message.unwrap)
                                    }
                                }
                                alert.show(persons: infos)
                            } else {
                                alertUtil(self, title: "该公司暂未维护催款人，请联系业务员", withCancel: false, operateS: [nameAction(name: "确定", action: { (_) in
                                    
                                })])
                            }
                        }
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
            }
            
        }
        return cell
    }
    
    func go2WLXX(index: Int) {
        let vc = ZyaLogisticsInfoVC()
        vc.model = self.dataArray[index]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    func network() {
        let api = API.queryLogistics(page: "\(self.page)", size: "\(KSGlobal.pageSize)", z_title: self.keyword, z_city: cityStr, z_begin_dt: self.startDate, z_end_dt: self.endDate, z_type: self.sourType, z_status: self.sourStatus, z_sort_type: sortType)
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZyaLogisticsModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infos {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < KSGlobal.pageSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                }
            } else {
                KSToast(data.message)
            }
        }
    }
    
    deinit {
        print("tenderfirst 销毁")
    }
    
}
